import time
import akshare as ak


def get_stock_realtime_price(stock_code="300502"):
    """
    获取指定A股股票的实时行情（最新价和涨跌幅）
    :param stock_code: 股票代码（如 "300502"）
    :return: dict，包含股票名称、最新价、涨跌幅
    """
    # 获取A股实时行情
    stock_df = ak.stock_zh_a_spot()

    # 筛选出目标股票
    stock_info = stock_df[stock_df["代码"] == stock_code]

    if stock_info.empty:
        return None

    result = {
        "名称": stock_info.iloc[0]["名称"],
        "最新价": stock_info.iloc[0]["最新价"],
        "涨跌幅": stock_info.iloc[0]["涨跌幅"]
    }
    return result


if __name__ == "__main__":
    # 循环获取，每隔5秒更新一次
    while True:
        stock_data = get_stock_realtime_price("300502")
        print(stock_data)
        # if stock_data:
        #     print(f"{stock_data['名称']} 当前价格: {stock_data['最新价']} 元, 涨跌幅: {stock_data['涨跌幅']}%")
        # else:
        #     print("未找到该股票代码，请检查输入。")
        # time.sleep(5)  # 每5秒刷新一次